﻿using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Linq;

namespace msBsc.SvRef
{

    public class SRWebClient
    {
        public CookieCollection cookie;
        public SRWebClient()
        {
            cookie = null;
        }

        #region 从包含多个 Cookie 的字符串读取到 CookieCollection 集合中
        private static void AddCookieWithCookieHead(ref CookieCollection cookieCol, string cookieHead, string defaultDomain)
        {
            if (cookieCol == null) cookieCol = new CookieCollection();
            if (cookieHead == null) return;
            string[] ary = cookieHead.Split(';');
            for (int i = 0; i < ary.Length; i++)
            {
                Cookie ck = GetCookieFromString(ary[i].Trim(), defaultDomain);
                if (ck != null)
                {
                    cookieCol.Add(ck);
                }
            }
        }
        #endregion

        #region 读取某一个 Cookie 字符串到 Cookie 变量中
        private static Cookie GetCookieFromString(string cookieString, string defaultDomain)
        {
            string[] ary = cookieString.Split(',');
            Hashtable hs = new Hashtable();
            for (int i = 0; i < ary.Length; i++)
            {
                string s = ary[i].Trim();
                int index = s.IndexOf("=");
                if (index > 0)
                {
                    hs.Add(s.Substring(0, index), s.Substring(index + 1));
                }
            }
            Cookie ck = new Cookie();
            foreach (object Key in hs.Keys)
            {
                if (Key.ToString() == "path") ck.Path = hs[Key].ToString();

                else if (Key.ToString() == "expires")
                {
                    //ck.Expires=DateTime.Parse(hs[Key].ToString();
                }
                else if (Key.ToString() == "domain") ck.Domain = hs[Key].ToString();
                else
                {
                    ck.Name = Key.ToString();
                    ck.Value = hs[Key].ToString();
                }
            }
            if (ck.Name == "") return null;
            if (ck.Domain == "") ck.Domain = defaultDomain;
            return ck;
        }
        #endregion

        
        /**/
        /// <TgData>
        ///     <Alias>下载Web源代码</Alias>
        /// </TgData>
        public string DownloadHtml(string URL, bool CreateCookie)
        {
            return DownloadHtml(URL, CreateCookie, System.Text.Encoding.Default);
        }

        /**/
        /// <TgData>
        ///     <Alias>下载Web源代码</Alias>
        /// </TgData>
        public string DownloadHtml(string URL, bool CreateCookie, System.Text.Encoding encode)
        {
            try
            {
                HttpWebRequest request = HttpWebRequest.Create(URL) as HttpWebRequest;
                if (cookie != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookie);
                }
                request.AllowAutoRedirect = false;
                //request.MaximumAutomaticRedirections = 3;
                request.Timeout = 20000;

                HttpWebResponse res = (HttpWebResponse)request.GetResponse();
                string r = "";

                System.IO.StreamReader S1 = new System.IO.StreamReader(res.GetResponseStream(), encode);
                try
                {
                    r = S1.ReadToEnd();
                    if (CreateCookie)
                        cookie = res.Cookies;
                }
                catch (Exception er)
                {
                    //Log l = new Log();
                    //l.writelog("下载Web错误", er.ToString());
                }
                finally
                {
                    res.Close();
                    S1.Close();
                }

                return r;
            }

            catch
            {

            }

            return string.Empty;
        }
         
        /**/
        /// <TgData>
        ///     <Alias>下载文件</Alias>
        /// </TgData>
        public long DownloadFile(string FileURL, string FileSavePath, bool CreateCookie)
        {
            long Filelength = 0;
            HttpWebRequest req = HttpWebRequest.Create(FileURL) as HttpWebRequest;

            if (cookie != null)
            {
                req.CookieContainer = new CookieContainer();
                req.CookieContainer.Add(cookie);
            }
            req.AllowAutoRedirect = true;

            try
            {
            HttpWebResponse res = req.GetResponse() as HttpWebResponse;
            if (CreateCookie)
                cookie = res.Cookies;
            System.IO.Stream stream = res.GetResponseStream();
                Filelength = res.ContentLength;

                byte[] b = new byte[512];

                int nReadSize = 0;
                nReadSize = stream.Read(b, 0, 512);

                 System.IO.FileInfo osaveinfo = new FileInfo(FileSavePath) ;
                if(!osaveinfo.Directory.Exists)
                {
                    System.IO.Directory.CreateDirectory(osaveinfo.Directory.FullName);
                }

                System.IO.FileStream fs = System.IO.File.Create(FileSavePath);
                try
                {
                    while (nReadSize > 0)
                    {
                        fs.Write(b, 0, nReadSize);
                        nReadSize = stream.Read(b, 0, 512);
                    }
                }
                finally
                {
                    fs.Close();
                res.Close();
                stream.Close();
                }
            }
            catch (Exception er)
            {
                //Log l = new Log();
                //l.writelog("下载文件错误", er.ToString());
            }
            finally
            {
            }

            return Filelength;
        }

        /**/
        /// <TgData>
        ///     <Alias>提交数据</Alias>
        /// </TgData>
        public string Request(string RequestPageURL, RequestData Data, bool CreateCookie)
        {
            StreamReader reader = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            try
            {
                string StrUrl = RequestPageURL;
                request = HttpWebRequest.Create(StrUrl) as HttpWebRequest;

                string postdata = Data.GetData();
                request.Referer = RequestPageURL;
                //request.AllowAutoRedirect = false;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                request.Timeout = 20000;

                if (cookie != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookie);
                }

                Uri u = new Uri(StrUrl);

                if (postdata.Length > 0) //包含要提交的数据　就使用Post方式
                {
                    request.ContentType = "application/x-www-form-urlencoded"; //作为表单请求
                    request.Method = "POST";        //方式就是Post

                    //把提交的数据换成字节数组
                    Byte[] B = System.Text.Encoding.UTF8.GetBytes(postdata);
                    request.ContentLength = B.Length;

                    System.IO.Stream SW = request.GetRequestStream(); //开始提交数据
                    SW.Write(B, 0, B.Length);
                    SW.Close();
                }

                response = request.GetResponse() as HttpWebResponse;
                if (CreateCookie)
                    //cookie = response.Cookies;
                    AddCookieWithCookieHead(ref cookie, response.Headers["Set-Cookie"], request.RequestUri.Host);
                reader = new StreamReader(response.GetResponseStream(), Encoding.Default);

                return reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                string x = ex.StackTrace;
            }
            finally
            {
                if (response != null)
                    response.Close();
            }

            return string.Empty;
        }


        public bool PostDownload(RequestData Data, out string file)
        {
            file = null;
            StreamReader reader = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            try
            {
                string StrUrl = "http://www.imobile.com.cn/wapdiyringdownload.php";
                request = HttpWebRequest.Create(StrUrl) as HttpWebRequest;

                string postdata = Data.GetData();
                request.Referer = StrUrl;
                request.AllowAutoRedirect = false;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                request.Timeout = 20000;

                if (cookie != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookie);
                }

                Uri u = new Uri(StrUrl);

                if (postdata.Length > 0) //包含要提交的数据　就使用Post方式
                {
                    request.ContentType = "application/x-www-form-urlencoded"; //作为表单请求
                    request.Method = "POST";        //方式就是Post

                    //把提交的数据换成字节数组
                    Byte[] B = System.Text.Encoding.UTF8.GetBytes(postdata);
                    request.ContentLength = B.Length;

                    System.IO.Stream SW = request.GetRequestStream(); //开始提交数据
                    SW.Write(B, 0, B.Length);
                    SW.Close();
                }

                response = request.GetResponse() as HttpWebResponse;
                string des = response.Headers["Content-Disposition"].Trim();
                file = des.Substring(des.IndexOf("filename=") + 9);
                file = new Random().Next(100).ToString() + "/" + file;

                System.IO.Stream stream = response.GetResponseStream();
                try
                {
                    int Filelength = (int)response.ContentLength;

                    byte[] b = new byte[512];

                    int nReadSize = 0;
                    nReadSize = stream.Read(b, 0, 512);

                    System.IO.FileStream fs = System.IO.File.Create("f:/mobileMusic/" + file);
                    try
                    {
                        while (nReadSize > 0)
                        {
                            fs.Write(b, 0, nReadSize);
                            nReadSize = stream.Read(b, 0, 512);
                        }
                    }
                    finally
                    {
                        fs.Close();
                    }
                }
                catch (Exception er)
                {
                    //Log l = new Log();
                    //l.writelog("下载文件错误", er.ToString());
                }
                finally
                {
                    response.Close();
                    stream.Close();
                }
            }
            catch (Exception ex)
            {
                string x = ex.StackTrace;
            }
            finally
            {
                if (response != null)
                    response.Close();
            }
            return true;
        }
        #region GetPage
        /// <summary>
        /// 获取源代码
        /// </summary>
        /// <param name="url"></param>
        /// <param name="coding"></param>
        /// <param name="TryCount"></param>
        /// <returns></returns>
        public static string GetPage(string url, Encoding encoding, int TryCount)
        {
            for (int i = 0; i < TryCount; i++)
            {
                string result = GetPage(url, encoding);
                if (result != null && result != string.Empty)
                    return result;
            }

            return string.Empty;
        }

        /// <summary>
        /// 获取源代码
        /// </summary>
        /// <param name="url"></param>
        /// <param name="coding"></param>
        /// <returns></returns>
        public static string GetPage(string url, Encoding encoding)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = 20000;
                request.AllowAutoRedirect = false;

                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
                {
                    reader = new StreamReader(response.GetResponseStream(), encoding);
                    string html = reader.ReadToEnd();

                    return html;
                }
            }
            catch
            {
            }
            finally
            {

                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (reader != null)
                    reader.Close();

                if (request != null)
                    request = null;

            }

            return string.Empty;
        }
        #endregion







        //public string GetLoginUserCry()
        //{
        //    string idName = string.Format("USER|{0};PASS|{1}", Epm.AppLogic.Framework.ApplicationInfo.Operator, Epm.AppLogic.Framework.ApplicationInfo.OperatorPass);
        //    idName = Epm.AppLogic.Framework.CUtil.EncryptionStringData(idName, Epm.AppLogic.Framework.CUtil.EncryptionType.RiJ);
        //    return idName;
        //}






        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeOut"></param>
        /// <param name="fileKeyName"></param>
        /// <param name="filePath"></param>
        /// <param name="stringDict">要传入的字符参数</param>
        /// <returns></returns>
        public  string HttpPostData(string url, int timeOut, string fileKeyName, string filePath, System.Collections.Specialized.NameValueCollection stringDict)
        {
            string responseContent;
            using (var memStream = new MemoryStream())
            {
                var webRequest = (HttpWebRequest)WebRequest.Create(url);    // 边界符  

                if (cookie != null)
                {
                    webRequest.CookieContainer = new CookieContainer();
                    webRequest.CookieContainer.Add(cookie);
                }

                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");    // 边界符  
                var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
                var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);    // 最后的结束符 
                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");    // 设置属性    
                webRequest.Method = "POST";
                webRequest.Timeout = timeOut;
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                // 写入文件  
                const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";
                var header = string.Format(filePartHeader, fileKeyName, filePath);
                var headerbytes = Encoding.UTF8.GetBytes(header);
                memStream.Write(beginBoundary, 0, beginBoundary.Length);
                memStream.Write(headerbytes, 0, headerbytes.Length);
                var buffer = new byte[1024];
                int bytesRead; // =0   
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
                // 写入字符串的Key  
                var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n";
                foreach (byte[] formitembytes in from string key in stringDict.Keys select string.Format(stringKeyHeader, key, stringDict[key]) into formitem select Encoding.UTF8.GetBytes(formitem))
                {
                    memStream.Write(formitembytes, 0, formitembytes.Length);
                }
                // 写入最后的结束边界符  
                memStream.Write(endBoundary, 0, endBoundary.Length);
                webRequest.ContentLength = memStream.Length;
                var requestStream = webRequest.GetRequestStream();
                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();
                var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
                using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    responseContent = httpStreamReader.ReadToEnd();
                }
                fileStream.Close();
                httpWebResponse.Close();
                webRequest.Abort();
                return responseContent;
            }
        }













    }

    public class RequestData
    {
        Hashtable hash = new Hashtable();

        public RequestData()
        {

        }

        public string GetData()
        {
            string r = "";

            foreach (string key in hash.Keys)
            {
                if (r.Length > 0) r += "&";
                r += key + "=" + hash[key];
            }

            return r;
        }

        public void AddField(string Field, string Value)
        {
            hash[Field] = Value;
        }


    }
}










 

            //SRWebClient client = new SRWebClient(); 
            //RequestData data1 = new RequestData();
            //data1.AddField("PjtID", "4394865");
            //data1.AddField("sbj_4487362[]", "319231");  
            //string result = client.Request("http://www.taeteacarnival.com/player/vote.jsp?id=1298&session=", data1, false);  
 




//客户端ip:

//Request.ServerVariables.Get("Remote_Addr").ToString();

//客户端主机名:

//Request.ServerVariables.Get("Remote_Host").ToString();

//客户端浏览器IE：

//Request.Browser.Browser;

//客户端浏览器 版本号：

//Request.Browser.MajorVersion;//

//客户端操作系统：

//Request.Browser.Platform;

//服务器ip:

//Request.ServerVariables.Get("Local_Addr").ToString();

//服务器名：

//Request.ServerVariables.Get("Server_Name").ToString();

//如果你想进一步了解ServerVariables，可以用

//   foreach(String o in Request.ServerVariables){

//    Response.Write(o+"="+Request.ServerVariables[o]+"<br>");

//   }

//=================================================

//Request.ServerVariables("Url")

//返回服务器地址

//Request.ServerVariables("Path_Info")

//客户端提供的路径信息

//Request.ServerVariables("Appl_Physical_Path")

//与应用程序元数据库路径相应的物理路径

//Request.ServerVariables("Path_Translated")

//通过由虚拟至物理的映射后得到的路径

//Request.ServerVariables("Script_Name")

//执行脚本的名称

//Request.ServerVariables("Query_String")

//查询字符串内容

//Request.ServerVariables("Http_Referer")

//请求的字符串内容

//Request.ServerVariables("Server_Port")

//接受请求的服务器端口号

//Request.ServerVariables("Remote_Addr")

//发出请求的远程主机的IP地址

//Request.ServerVariables("Remote_Host")

//发出请求的远程主机名称

//Request.ServerVariables("Local_Addr")

//返回接受请求的服务器地址

//Request.ServerVariables("Http_Host")

//返回服务器地址

//Request.ServerVariables("Server_Name")

//服务器的主机名、DNS地址或IP地址

//Request.ServerVariables("Request_Method")

//提出请求的方法比如GET、HEAD、POST等等

//Request.ServerVariables("Server_Port_Secure")

//如果接受请求的服务器端口为安全端口时，则为1，否则为0

//Request.ServerVariables("Server_Protocol")

//服务器使用的协议的名称和版本

//Request.ServerVariables("Server_Software")

//应答请求并运行网关的服务器软件的名称和版本

//Request.ServerVariables("All_Http")

//客户端发送的所有HTTP标头，前缀HTTP_

//Request.ServerVariables("All_Raw")

//客户端发送的所有HTTP标头,其结果和客户端发送时一样，没有前缀HTTP_

//Request.ServerVariables("Appl_MD_Path")

//应用程序的元数据库路径

//Request.ServerVariables("Content_Length")

//客户端发出内容的长度

//Request.ServerVariables("Https")

//如果请求穿过安全通道（SSL），则返回ON如果请求来自非安全通道，则返回OFF

//Request.ServerVariables("Instance_ID")

//IIS实例的ID号

//Request.ServerVariables("Instance_Meta_Path")

//响应请求的IIS实例的元数据库路径

//Request.ServerVariables("Http_Accept_Encoding")

//返回内容如：gzip,deflate

//Request.ServerVariables("Http_Accept_Language")

//返回内容如：en-us

//Request.ServerVariables("Http_Connection")

//返回内容：Keep-Alive

//Request.ServerVariables("Http_Cookie")

//返回内容如：nVisiT%2DYum=125;ASPSESSIONIDCARTQTRA=FDOBFFABJGOECBBKHKGPFIJI;ASPSESSIONIDCAQQTSRB=LKJJPLABABILLPCOGJGAMKAM;ASPSESSIONIDACRRSSRA=DKHHHFBBJOJCCONPPHLKGHPB

//Request.ServerVariables("Http_User_Agent")

//返回内容：Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)

//Request.ServerVariables("Https_Keysize")

//安全套接字层连接关键字的位数，如128

//Request.ServerVariables("Https_Secretkeysize")

//服务器验证私人关键字的位数如1024

//Request.ServerVariables("Https_Server_Issuer")

//服务器证书的发行者字段

//Request.ServerVariables("Https_Server_Subject")

//服务器证书的主题字段

//Request.ServerVariables("Auth_Password")

//当使用基本验证模式时，客户在密码对话框中输入的密码

//Request.ServerVariables("Auth_Type")

//是用户访问受保护的脚本时，服务器用於检验用户的验证方法

//Request.ServerVariables("Auth_User")

//代证的用户名

//Request.ServerVariables("Cert_Cookie")

//唯一的客户证书ID号

//Request.ServerVariables("Cert_Flag")

//客户证书标志，如有客户端证书，则bit0为0如果客户端证书验证无效，bit1被设置为1

//Request.ServerVariables("Cert_Issuer")

//用户证书中的发行者字段

//Request.ServerVariables("Cert_Keysize")

//安全套接字层连接关键字的位数，如128

//Request.ServerVariables("Cert_Secretkeysize")

//服务器验证私人关键字的位数如1024

//Request.ServerVariables("Cert_Serialnumber")

//客户证书的序列号字段

//Request.ServerVariables("Cert_Server_Issuer")

//服务器证书的发行者字段

//Request.ServerVariables("Cert_Server_Subject")

//服务器证书的主题字段

//Request.ServerVariables("Cert_Subject")

//客户端证书的主题字段

//Request.ServerVariables("Content_Type")

//客户发送的form内容或HTTPPUT的数据类型